package com.ys.service.report.impl;

import com.ys.entity.business.TpProductBasisComponent;
import com.ys.entity.finance.TcwAccountCountForCompanyHistory;
import com.ys.entity.report.TcoBusinessDataGs;
import com.ys.entity.report.TcoBusinessDataStat;
import com.ys.entity.report.TcoBusinessDataStatForCount;
import com.ys.enume.purchase.TcgOfflinePurchaseInStorageEnum;
import com.ys.mapper.report.ReportMapper;
import com.ys.mapper.report.TcoBusinessDataStatMapper;
import com.ys.service.report.TcoBusinessDataStatService;
import com.ys.util.DateUtil;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

//运营数据统计表
@Service("tcoBusinessDataStatService")
public class TcoBusinessDataStatServiceImpl implements TcoBusinessDataStatService {
	private static final Logger logger = LoggerFactory.getLogger(TcoBusinessDataStatServiceImpl.class);
	@Autowired
	private TcoBusinessDataStatMapper tcoBusinessDataStatMapper;

	@Autowired
	private ReportMapper reportMapper;

	/**
	 * 根据月份刷取数据
	 */
	@Override
	public void count(String countMonth)throws Exception{

		//获取这个月的数据
		String thisMonth = DateUtil.getYYYY_MM(new Date());

		//获取统计月份的上一个月的日期
		String oldMonthByCount = DateUtil.getYYYY_MM(DateUtil.addMonth(countMonth,-1));


		//获取需要统计的公司信息
		List<Map<String,Object>> gsList = new ArrayList<>();

		//旧月份数据
		List<Map<String,Object>> oldMonthList = new ArrayList<>();

		boolean isNowMonth = false;//是否是本月
		boolean isAllReCount = false;//是否全部重新计算
		if(thisMonth.equals(countMonth)){
			isNowMonth = true;
			isAllReCount =  true;
		}
		if(isNowMonth){//如果是当前月份
			gsList = new TcoBusinessDataGs()
					.addLeftJoin("THR_OperateCompanyApply B ON B.Vgsbm = A.Vgsbm")
					.addField("B.Vgsjc AS vgsjc")
					.queryMap();
		}else {
			//如果非当前月份
			List<Map<String,Object>> dataStatList = new TcoBusinessDataStat().setCountMonth(countMonth).queryMap();
			if(dataStatList!=null && dataStatList.size()>0){//如果有旧数据，则按旧数据的公司信息
				gsList = dataStatList;
				oldMonthList = dataStatList;
			}else {
				//否则还是获取维护的信息
				gsList =  new TcoBusinessDataGs()
						.addLeftJoin("THR_OperateCompanyApply B ON B.Vgsbm = A.Vgsbm")
						.addField("B.Vgsjc AS vgsjc")
						.queryMap();
			}
		}


		//如果旧月份数据为空，则和本月数据一样，都要全部重新刷取
		if(oldMonthList==null || oldMonthList.size()<=0){
			isAllReCount =  true;
		}

		//先删除该月数据
		reportMapper.deleteBusinessDataStatByMonth(countMonth);
		reportMapper.deleteBusinessDataStatForCountByMonth(countMonth);

		if(gsList!=null && gsList.size()>0){
			List<TcoBusinessDataStat> countList = new ArrayList<>();

			//获取月份最后一天
			int lastDay = DateUtil.getMonthLastDay(countMonth);

			//*********************** 1、获取订单日报表的统计数据：订单数、销售金额、日均订单数 ***********************
			List<Map<String, Object>> countOrderNumAndSaleAmount = reportMapper.countOrderNumAndSaleAmountByOrderDetail(countMonth+"-01", countMonth+"-"+lastDay);

			//*********************** 2、获取流水统计数据，根据交易类型、审核时间 ***********************
			String startTime = countMonth+"-01 "+"00:00:00";
			String endTime = countMonth+"-"+lastDay+" 23:59:59";
			List<Map<String, Object>> countCostAmountByJylx = reportMapper.countCostAmountByJylx(startTime, endTime);

			//*********************** 3、获取公司历史资金 ***********************
			String searchDay =countMonth+"-"+lastDay;
			if(isNowMonth){//如果是当前月份
				//获取昨天日期
				searchDay =  DateUtil.getYYYY_MM_DD(DateUtil.addDays(new Date(), -1));
			}
			String searchDayEnd = DateUtil.getYYYY_MM_DD(DateUtil.addDays(searchDay, 1));
			List<TcwAccountCountForCompanyHistory> historyList = new TcwAccountCountForCompanyHistory()
					.where("A.GDate BETWEEN '"+searchDay+"' AND '"+searchDayEnd+"'")
					.queryList();

			//TODO 亚马逊余额 API???
			//***********************  5、获取Listing库子件信息 ***********************
			List<TpProductBasisComponent> productBasisComponentList = new TpProductBasisComponent().queryList();

			//***********************  4、获取库存总数 - Amazon商品管理 统计数据 ***********************
			List<Map<String, Object>> counTpAmazonShopProductList = reportMapper.counTpAmazonShopProduct();

			//***********************  6、获取库存数量 ***********************
			List<Map<String, Object>> counStockControlList = reportMapper.counTccStockControlByBusinessDataStat();

			//***********************  7、获取采购未入库数量 ***********************
			List<Map<String, Object>> purchaseInStorageList = reportMapper.counPurchaseInStorageByBusinessDataStat(TcgOfflinePurchaseInStorageEnum.StorageStatus.STOCK_PENDING.value);

			//库存总额

			//预估价值

			//***********************  8、遍历公司信息，并填入统计表信息 ***********************
			for(Map<String,Object> gsItem:gsList){
				String vgsbm = gsItem.get("vgsbm").toString();
				String vgsjc= gsItem.get("vgsjc").toString();
				TcoBusinessDataStat tcoBusinessDataStat = new TcoBusinessDataStat();

				//***********************  (1)、计算：订单数、销售金额、日均订单数 ***********************
				BigDecimal orderNum = BigDecimal.ZERO;//订单数
				BigDecimal saleAmount = BigDecimal.ZERO;//销售金额
				BigDecimal orderNumByDay = BigDecimal.ZERO;//日均订单数
				List<Map<String, Object>> countOrderNumAndSaleAmountByGs = countOrderNumAndSaleAmount.stream()
						.filter(e->e.get("vgsbm")!=null && e.get("vgsbm").toString().equals(vgsbm)).collect(Collectors.toList());
				if(countOrderNumAndSaleAmountByGs.size()>0){
					for(Map<String, Object> countItem:countOrderNumAndSaleAmountByGs){
						//累加 订单数
						if(countItem.get("quantityOrdered")!=null && !"".equals(countItem.get("quantityOrdered"))){
							orderNum = orderNum.add(new BigDecimal(countItem.get("quantityOrdered").toString()));
						}
						//累加 销售金额
						if(countItem.get("orderMoney")!=null && !"".equals(countItem.get("orderMoney"))){
							saleAmount = saleAmount.add(new BigDecimal(countItem.get("orderMoney").toString()));
						}
					}
				}
				if(orderNum.compareTo(BigDecimal.ZERO)!=0){
					int countDay = lastDay;
					if(isNowMonth) {//如果是当前月份，则日均天数算到作天为止
						Calendar c = Calendar.getInstance();
						c.setTime(DateUtil.addDays(new Date(),-1));
						countDay = c.get(Calendar.DAY_OF_MONTH);
					}
					orderNumByDay = orderNum.divide(new BigDecimal(countDay),2,BigDecimal.ROUND_HALF_UP);
				}

				//***********************  (2)、计算：采购成本 ***********************
				BigDecimal purchaseCostAmount = BigDecimal.ZERO;//采购成本
				List<Map<String, Object>> purchaseCostAmountList = countCostAmountByJylx.stream()
						.filter(e->e.get("vgsbm")!=null && e.get("vgsbm").toString().equals(vgsbm) && e.get("vjylx")!=null && e.get("vjylx").toString().contains("采购服务→")).collect(Collectors.toList());
				for(Map<String, Object> countItem:purchaseCostAmountList){
					if(countItem.get("fje")!=null && !"".equals(countItem.get("fje"))){//累加
						purchaseCostAmount = purchaseCostAmount.add(new BigDecimal(countItem.get("fje").toString()));
					}
				}

				//***********************  (3)、计算：仓储成本 ***********************
				BigDecimal storageCostAmount = BigDecimal.ZERO;//仓储成本
				List<Map<String, Object>> storageCostAmountList = countCostAmountByJylx.stream()
						.filter(e->e.get("vgsbm")!=null && e.get("vgsbm").toString().equals(vgsbm) && e.get("vjylx")!=null && e.get("vjylx").toString().contains("仓储服务→")).collect(Collectors.toList());
				for(Map<String, Object> countItem:storageCostAmountList){
					if(countItem.get("fje")!=null && !"".equals(countItem.get("fje"))){//累加
						storageCostAmount = storageCostAmount.add(new BigDecimal(countItem.get("fje").toString()));
					}
				}

				//***********************  (4)、计算：运输成本 ***********************
				BigDecimal transportCostAmount = BigDecimal.ZERO;//仓储成本
				List<Map<String, Object>> transportCostAmountList = countCostAmountByJylx.stream()
						.filter(e->e.get("vgsbm")!=null && e.get("vgsbm").toString().equals(vgsbm) && e.get("vjylx")!=null && e.get("vjylx").toString().contains("物流服务→")).collect(Collectors.toList());
				for(Map<String, Object> countItem:transportCostAmountList){
					if(countItem.get("fje")!=null && !"".equals(countItem.get("fje"))){//累加
						transportCostAmount = transportCostAmount.add(new BigDecimal(countItem.get("fje").toString()));
					}
				}


				//***********************  (5)、计算：运营成本 ***********************
				BigDecimal businessCostAmount = BigDecimal.ZERO;//运营成本
				List<Map<String, Object>> businessCostAmountList = countCostAmountByJylx.stream()
						.filter(e->
								e.get("vgsbm")!=null && e.get("vgsbm").toString().equals(vgsbm) && e.get("vjylx")!=null
								&& (
										e.get("vjylx").toString().contains("产品服务→")
										|| e.get("vjylx").toString().equals("运营服务→管理绩效")
										|| e.get("vjylx").toString().equals("运营服务→管理绩效分配")
										|| e.get("vjylx").toString().equals("运营服务→划拨费用")
										|| e.get("vjylx").toString().equals("运营服务→经营理赔款项")
										|| e.get("vjylx").toString().equals("运营服务→预付款退回")
										|| e.get("vjylx").toString().equals("运营服务→运营服务费")
								)
						).collect(Collectors.toList());
				for(Map<String, Object> countItem:businessCostAmountList){
					if(countItem.get("fje")!=null && !"".equals(countItem.get("fje"))){//累加
						businessCostAmount = businessCostAmount.add(new BigDecimal(countItem.get("fje").toString()));
					}
				}


				//***********************  (6)、计算：店铺回款 ***********************
				BigDecimal shopBackAmount = BigDecimal.ZERO;//店铺回款
				List<Map<String, Object>> shopBackAmountList = countCostAmountByJylx.stream()
						.filter(e->
								e.get("vgsbm")!=null && e.get("vgsbm").toString().equals(vgsbm) && e.get("vjylx")!=null
								&& (
										e.get("vjylx").toString().contains("运营服务→店铺回款")
										|| e.get("vjylx").toString().equals("运营服务→预付款（店铺回款）")
								)
						).collect(Collectors.toList());
				for(Map<String, Object> countItem:shopBackAmountList){
					if(countItem.get("fje")!=null && !"".equals(countItem.get("fje"))){//累加
						shopBackAmount = shopBackAmount.add(new BigDecimal(countItem.get("fje").toString()));
					}
				}



				if(isAllReCount) {//如果全部重新计算 ,才需要重新计算的数值
					//***********************  (7)、计算：ERP余额 ***********************
					BigDecimal erpSurplusAmount = BigDecimal.ZERO;//ERP余额
					List<TcwAccountCountForCompanyHistory> erpSurplusAmountByGs = historyList.stream()
							.filter(e->e.getVGsBm()!=null && e.getVGsBm().equals(vgsbm)).collect(Collectors.toList());
					if(erpSurplusAmountByGs.size()>0){
						erpSurplusAmount = erpSurplusAmountByGs.get(0).getFJe();
					}


					//***********************  (8)、计算：库存总数 ***********************
					//运营数据统计表-商品数量
					List<TcoBusinessDataStatForCount> productList = new ArrayList<>();

					//***********************  (8.1)、计算：库存总数 => Amazon商品管理 ***********************
					BigDecimal stockNumByAmazonProduct = BigDecimal.ZERO;//库存总数 => Amazon商品管理
					//Amazon商品管理
					List<Map<String, Object>> countTpAmazonShopProductByGs = counTpAmazonShopProductList.stream()
							.filter(e->e.get("vgsbm")!=null && e.get("vgsbm").toString().equals(vgsbm)).collect(Collectors.toList());
					if(countTpAmazonShopProductByGs.size()>0){
						for(Map<String, Object> countItem:countTpAmazonShopProductByGs){
							if(countItem.get("code")!=null && !"".equals(countItem.get("code")) && countItem.get("totalNum")!=null && !"".equals(countItem.get("totalNum"))){
								String code = countItem.get("code").toString();//商品编码
								BigDecimal totalNum = new BigDecimal(countItem.get("totalNum").toString());//数量
								stockNumByAmazonProduct = stockNumByAmazonProduct.add(totalNum);//累加
								//将母件商品与数量记录（新增或累加）至：运营数据统计表-商品数量 表中
								boolean isAdded = false;//是否已新增过的标识
								if(productList.size()>0){
									List<TcoBusinessDataStatForCount> productListByNew = new ArrayList<>();
									for(TcoBusinessDataStatForCount tcoBusinessDataStatForCount:productList){
										if(tcoBusinessDataStatForCount.getProductCode().equals(code)){//若新增过，则累加
											tcoBusinessDataStatForCount.setProductNum((new BigDecimal(tcoBusinessDataStatForCount.getProductNum()).add(totalNum)).intValue());
											isAdded = true;
										}
										productListByNew.add(tcoBusinessDataStatForCount);
									}
									productList = productListByNew;
								}
								if(!isAdded){//未新增过，新填入
									TcoBusinessDataStatForCount tcoBusinessDataStatForCount = new TcoBusinessDataStatForCount();
									tcoBusinessDataStatForCount.setProductCode(code);
									tcoBusinessDataStatForCount.setProductNum(totalNum.intValue());
									productList.add(tcoBusinessDataStatForCount);
								}
							}
						}
					}

					//***********************  (8.2)、计算：库存总数 => 库存数量 ***********************
					//库存数量
					BigDecimal stockNumByStockNum = BigDecimal.ZERO;//库存总数 => 库存数量
					List<Map<String, Object>> counStockControlListByGs = counStockControlList.stream()
							.filter(e->e.get("vgsbm")!=null && e.get("vgsbm").toString().equals(vgsbm)).collect(Collectors.toList());
					if(countTpAmazonShopProductByGs.size()>0){
						for(Map<String, Object> countItem:counStockControlListByGs){
							if(countItem.get("code")!=null && !"".equals(countItem.get("code")) && countItem.get("totalNum")!=null && !"".equals(countItem.get("totalNum"))){
								String code = countItem.get("code").toString();//商品编码
								BigDecimal totalNum = new BigDecimal(countItem.get("totalNum").toString());//数量
								stockNumByStockNum = stockNumByStockNum.add(totalNum);//累加
								//将母件商品与数量记录（新增或累加）至：运营数据统计表-商品数量 表中
								boolean isAdded = false;//是否已新增过的标识
								if(productList.size()>0){
									List<TcoBusinessDataStatForCount> productListByNew = new ArrayList<>();
									for(TcoBusinessDataStatForCount tcoBusinessDataStatForCount:productList){
										if(tcoBusinessDataStatForCount.getProductCode().equals(code)){//若新增过，则累加
											tcoBusinessDataStatForCount.setProductNum((new BigDecimal(tcoBusinessDataStatForCount.getProductNum()).add(totalNum)).intValue());
											isAdded = true;
										}
										productListByNew.add(tcoBusinessDataStatForCount);
									}
									productList = productListByNew;
								}
								if(!isAdded){//未新增过，新填入
									TcoBusinessDataStatForCount tcoBusinessDataStatForCount = new TcoBusinessDataStatForCount();
									tcoBusinessDataStatForCount.setProductCode(code);
									tcoBusinessDataStatForCount.setProductNum(totalNum.intValue());
									productList.add(tcoBusinessDataStatForCount);
								}
							}
						}
					}

					//***********************  (8.3)、计算：库存总数 => 采购未入库数量 ***********************
					BigDecimal cgNotInStockNum = BigDecimal.ZERO;//库存总数 => 采购未入库数量
					List<Map<String, Object>> cgNotInStockListByGs = purchaseInStorageList.stream()
							.filter(e->e.get("vgsbm")!=null && e.get("vgsbm").toString().equals(vgsbm)).collect(Collectors.toList());
					if(countTpAmazonShopProductByGs.size()>0){
						for(Map<String, Object> countItem:cgNotInStockListByGs){
							if(countItem.get("code")!=null && !"".equals(countItem.get("code")) && countItem.get("totalNum")!=null && !"".equals(countItem.get("totalNum"))){
								String code = countItem.get("code").toString();//商品编码
								BigDecimal totalNum = new BigDecimal(countItem.get("totalNum").toString());//数量
								cgNotInStockNum = cgNotInStockNum.add(totalNum);//累加
								//将母件商品与数量记录（新增或累加）至：运营数据统计表-商品数量 表中
								boolean isAdded = false;//是否已新增过的标识
								if(productList.size()>0){
									List<TcoBusinessDataStatForCount> productListByNew = new ArrayList<>();
									for(TcoBusinessDataStatForCount tcoBusinessDataStatForCount:productList){
										if(tcoBusinessDataStatForCount.getProductCode().equals(code)){//若新增过，则累加
											tcoBusinessDataStatForCount.setProductNum((new BigDecimal(tcoBusinessDataStatForCount.getProductNum()).add(totalNum)).intValue());
											isAdded = true;
										}
										productListByNew.add(tcoBusinessDataStatForCount);
									}
									productList = productListByNew;
								}
								if(!isAdded){//未新增过，新填入
									TcoBusinessDataStatForCount tcoBusinessDataStatForCount = new TcoBusinessDataStatForCount();
									tcoBusinessDataStatForCount.setProductCode(code);
									tcoBusinessDataStatForCount.setProductNum(totalNum.intValue());
									productList.add(tcoBusinessDataStatForCount);
								}
							}
						}
					}

					BigDecimal stockNum  = stockNumByAmazonProduct.add(stockNumByStockNum).add(cgNotInStockNum);//库存总数 = Amazon商品管理 + 库存数量 + 采购未入库数量


					//***********************  (9)、计算：库存总额 = 商品数量*Listing（子件数量*子件单价之和） ***********************
					BigDecimal stockProductNum = BigDecimal.ZERO;//库存总额
					if(productList.size()>0 && productBasisComponentList!=null && productBasisComponentList.size()>0){
						List<TcoBusinessDataStatForCount> productListByNew = new ArrayList<>();
						for(TcoBusinessDataStatForCount tcoBusinessDataStatForCount:productList){
							tcoBusinessDataStatForCount.setCountMonth(countMonth);
							tcoBusinessDataStatForCount.setStatus(1);
							//获取商品编码对应子件信息
							List<TpProductBasisComponent> productBasisComponentListByCode = productBasisComponentList.stream().filter(e->e.getPcode().equals(tcoBusinessDataStatForCount.getProductCode())).collect(Collectors.toList());
							BigDecimal subAmount = BigDecimal.ZERO;//子件总价
							if(productBasisComponentListByCode.size()>0){
								for(TpProductBasisComponent componentItem:productBasisComponentListByCode){
									if(componentItem.getBprice()!=null && componentItem.getNum()!=null){
										subAmount = subAmount.add(componentItem.getBprice().multiply(componentItem.getNum()));//子件总价 = 子件单价*数量
									}
								}
							}
							tcoBusinessDataStatForCount.setSubAmount(subAmount.setScale(2,BigDecimal.ROUND_HALF_UP));
							productListByNew.add(tcoBusinessDataStatForCount);
						}
						productList = productListByNew;
					}

					//批量新增：运营数据统计表-商品数量 表
					int pageNm = 50;
					//所以分批插入,一次插入pageNm
					for(int i=0;i<productList.size()+pageNm;i=i+pageNm){
						//批量新增
						List<TcoBusinessDataStatForCount> addlist = productList.stream().skip(i).limit(pageNm).collect(Collectors.toList());
						reportMapper.insertBusinessDataStatForCountBatch(addlist);
					}

					//计算 库存总额
					if(productList.size()>0){
						for(TcoBusinessDataStatForCount tcoBusinessDataStatForCount:productList){
							stockProductNum = stockProductNum.add(
									new BigDecimal(tcoBusinessDataStatForCount.getProductNum()).multiply(tcoBusinessDataStatForCount.getSubAmount())//商品数量 * 子件总价
							);
						}
					}

					BigDecimal awsSurplusAmount = BigDecimal.ZERO;//亚马逊余额
					tcoBusinessDataStat.setErpSurplusAmount(erpSurplusAmount);//ERP余额
					tcoBusinessDataStat.setStockNum(stockNum.intValue());//库存总数
					tcoBusinessDataStat.setStockProductNum(stockProductNum.setScale(2,BigDecimal.ROUND_HALF_UP));//库存总额
					tcoBusinessDataStat.setEstimateAmount(erpSurplusAmount.add(awsSurplusAmount).add(tcoBusinessDataStat.getStockProductNum()));//预估价值 = ERP余额+亚马逊余额+库存总额

				}else {
					List<Map<String,Object>> oldMonthListByGs =  oldMonthList.stream()
							.filter(e->e.get("vgsbm")!=null && e.get("vgsbm").toString().equals(vgsbm)).collect(Collectors.toList());
					if(oldMonthListByGs.size()>0){
						Map<String,Object> itemByGs = oldMonthListByGs.get(0);
						BigDecimal awsSurplusAmount = itemByGs.get("awsSurplusAmount")!=null?new BigDecimal(itemByGs.get("awsSurplusAmount").toString()):BigDecimal.ZERO;//亚马逊余额
						tcoBusinessDataStat.setErpSurplusAmount(new BigDecimal(itemByGs.get("erpSurplusAmount").toString()));//ERP余额
						tcoBusinessDataStat.setStockNum(new BigDecimal(itemByGs.get("stockNum").toString()).intValue());//库存总数
						tcoBusinessDataStat.setStockProductNum(new BigDecimal(itemByGs.get("stockProductNum").toString()));//库存总额
						tcoBusinessDataStat.setEstimateAmount(tcoBusinessDataStat.getErpSurplusAmount().add(awsSurplusAmount).add(tcoBusinessDataStat.getStockProductNum()));//预估价值 = ERP余额+亚马逊余额+库存总额
					}else {
						tcoBusinessDataStat.setErpSurplusAmount(BigDecimal.ZERO);//ERP余额
						tcoBusinessDataStat.setStockNum(0);//库存总数
						tcoBusinessDataStat.setStockProductNum(BigDecimal.ZERO);//库存总额
						tcoBusinessDataStat.setEstimateAmount(BigDecimal.ZERO);//预估价值
					}
				}

				tcoBusinessDataStat.setVgsbm(vgsbm);//所属公司编码
				tcoBusinessDataStat.setVgsjc(vgsjc);//所属公司简称
				tcoBusinessDataStat.setCountMonth(countMonth);//统计月份
				tcoBusinessDataStat.setLastMonth(oldMonthByCount);//上个月
				tcoBusinessDataStat.setCountYear(countMonth.substring(0,4));//统计所在的年份
				tcoBusinessDataStat.setOrderNum(orderNum.intValue());//订单数
				tcoBusinessDataStat.setSaleAmount(saleAmount);//销售金额
				tcoBusinessDataStat.setOrderNumByDay(orderNumByDay);//日均订单数
				tcoBusinessDataStat.setPurchaseCostAmount(purchaseCostAmount);//采购成本
				tcoBusinessDataStat.setStorageCostAmount(storageCostAmount);//仓储成本
				tcoBusinessDataStat.setTransportCostAmount(transportCostAmount);//运输成本
				tcoBusinessDataStat.setBusinessCostAmount(businessCostAmount);//运营成本
				tcoBusinessDataStat.setShopBackAmount(shopBackAmount);//店铺回款




				tcoBusinessDataStat.setStatus(1);//状态
				countList.add(tcoBusinessDataStat);
			}

			//批量新增：运营数据统计表
			int pageNm = 50;
			//所以分批插入,一次插入pageNm
			for(int i=0;i<countList.size()+pageNm;i=i+pageNm){
				//批量新增
				List<TcoBusinessDataStat> addlist = countList.stream().skip(i).limit(pageNm).collect(Collectors.toList());
				reportMapper.insertBusinessDataStatBatch(addlist);
			}

		}


	}



	/**
	 * 刷取年累计数据
	 */
	@Override
	public void countYearAdded(String countMonth)throws Exception{
		String yearStr = countMonth.substring(0,4);
		String monthStart = yearStr+"-01";

		//获取今年的统计数据
		List<TcoBusinessDataStat> nowYearCountList = new TcoBusinessDataStat()
				.setCountYear(yearStr)
				.where("A.CountMonth BETWEEN '"+monthStart+"' AND '"+countMonth+"'")
				.queryList();

		//获取需要修改的月的统计数据
		List<TcoBusinessDataStat> nowMonthCountList = new TcoBusinessDataStat().setCountMonth(countMonth).queryList();

		if(nowMonthCountList!=null && nowMonthCountList.size()>0 && nowYearCountList!=null && nowYearCountList.size()>0){
			for(TcoBusinessDataStat tcoBusinessDataStat:nowMonthCountList){
				String vgsbm = tcoBusinessDataStat.getVgsbm();
				BigDecimal yearOrderNum = BigDecimal.ZERO;//订单数（年度累计）
				BigDecimal yearSaleAmount = BigDecimal.ZERO;//销售金额（年度累计）
				BigDecimal yearOrderNumByDay = BigDecimal.ZERO;//日均订单数（年度累计）
				BigDecimal yearPurchaseCostAmount = BigDecimal.ZERO;//采购成本（年度累计）
				BigDecimal yearStorageCostAmount = BigDecimal.ZERO;//仓储成本（年度累计）
				BigDecimal yearTransportCostAmount = BigDecimal.ZERO;//运输成本（年度累计）
				BigDecimal yearBusinessCostAmount = BigDecimal.ZERO;//运营成本（年度累计）
				BigDecimal yearShopBackAmount = BigDecimal.ZERO;//店铺回款（年度累计）

				List<TcoBusinessDataStat> nowYearCountListByGs = nowYearCountList.stream().filter(e->e.getVgsbm().equals(vgsbm)).collect(Collectors.toList());
				if(nowYearCountListByGs.size()>0){
					for(TcoBusinessDataStat yearCountItem:nowYearCountListByGs){
						if(yearCountItem.getOrderNum()!=null) yearOrderNum = yearOrderNum.add(new BigDecimal(yearCountItem.getOrderNum()));
						if(yearCountItem.getSaleAmount()!=null) yearSaleAmount = yearSaleAmount.add(yearCountItem.getSaleAmount());
						if(yearCountItem.getOrderNumByDay()!=null) yearOrderNumByDay = yearOrderNumByDay.add(yearCountItem.getOrderNumByDay());
						if(yearCountItem.getPurchaseCostAmount()!=null) yearPurchaseCostAmount = yearPurchaseCostAmount.add(yearCountItem.getPurchaseCostAmount());
						if(yearCountItem.getStorageCostAmount()!=null) yearStorageCostAmount = yearStorageCostAmount.add(yearCountItem.getStorageCostAmount());
						if(yearCountItem.getTransportCostAmount()!=null) yearTransportCostAmount = yearTransportCostAmount.add(yearCountItem.getTransportCostAmount());
						if(yearCountItem.getBusinessCostAmount()!=null) yearBusinessCostAmount = yearBusinessCostAmount.add(yearCountItem.getBusinessCostAmount());
						if(yearCountItem.getShopBackAmount()!=null) yearShopBackAmount = yearShopBackAmount.add(yearCountItem.getShopBackAmount());
					}
				}

				tcoBusinessDataStat.setYearOrderNum(yearOrderNum.intValue());//订单数（年度累计）
				tcoBusinessDataStat.setYearSaleAmount(yearSaleAmount);//销售金额（年度累计）
				tcoBusinessDataStat.setYearOrderNumByDay(yearOrderNumByDay);//日均订单数（年度累计）
				tcoBusinessDataStat.setYearPurchaseCostAmount(yearPurchaseCostAmount);//采购成本（年度累计）
				tcoBusinessDataStat.setYearStorageCostAmount(yearStorageCostAmount);//仓储成本（年度累计）
				tcoBusinessDataStat.setYearTransportCostAmount(yearTransportCostAmount);//运输成本（年度累计）
				tcoBusinessDataStat.setYearBusinessCostAmount(yearBusinessCostAmount);//运营成本（年度累计）
				tcoBusinessDataStat.setYearShopBackAmount(yearShopBackAmount);//店铺回款（年度累计）

				tcoBusinessDataStatMapper.update(tcoBusinessDataStat);
			}
		}

	}







	//删除前3个月数据
	public void delOldMonthData(String countMonth)throws Exception{
		//删除前3个月数据
		String oldMonth = DateUtil.getYYYY_MM(DateUtil.addMonth(countMonth,-3));
		reportMapper.deleteBusinessDataStatForCountOldMonth(oldMonth);
	}

	//编辑亚马逊余额
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R editAwsSurplusAmount(Long id, String awsSurplusAmount) throws Exception {
		TcoBusinessDataStat entity = new TcoBusinessDataStat().setId(id).queryFirst();
		if(entity!=null && entity.getId()!=null){
			entity.setAwsSurplusAmount(new BigDecimal(awsSurplusAmount));
			entity.setEstimateAmount(entity.getErpSurplusAmount().add(entity.getAwsSurplusAmount()).add(entity.getStockProductNum()));//预估价值 = ERP余额+亚马逊余额+库存总额
			tcoBusinessDataStatMapper.update(entity);
		}else {
			return R.error("数据有误");
		}
		return R.ok();
	}
}
